<template>
  <div class="channel-container">
    <div v-if="loadingUser" class="loading-placeholder">
      <el-skeleton animated>
        <template #template>
          <div class="channel-header-skeleton">
            <el-skeleton-item variant="circle" style="width: 80px; height: 80px;" />
            <div style="flex: 1;">
              <el-skeleton-item variant="h3" style="width: 50%; margin-bottom: 10px;" />
              <el-skeleton-item variant="text" style="width: 30%;" />
            </div>
          </div>
        </template>
      </el-skeleton>
    </div>
    
    <div v-else-if="user" class="channel-content">
      <div class="channel-header">
        <el-avatar :size="80" :src="user.avatar">
          <el-icon><User /></el-icon>
        </el-avatar>
        <div class="channel-info">
          <h2 class="channel-name">{{ user.username }}</h2>
          <div class="channel-stats">
            <span>{{ formatSubscribers(user.subscribers?.length || 0) }} 位订阅者</span>
            <span v-if="user.stats">{{ formatViews(user.stats.totalViews || 0) }} 次观看</span>
          </div>
          <div class="channel-bio" v-if="user.bio">{{ user.bio }}</div>
          
          <el-button
            v-if="isLoggedIn && currentUser?._id !== user._id"
            :type="isSubscribed ? 'info' : 'danger'"
            round
            @click="toggleSubscription"
            :loading="subscribing"
          >
            {{ isSubscribed ? '已订阅' : '订阅' }}
          </el-button>
        </div>
      </div>
      
      <el-tabs v-model="activeTab" class="channel-tabs">
        <el-tab-pane label="视频" name="videos">
          <div v-if="loadingVideos" class="loading-content">
            <el-skeleton :rows="3" animated />
          </div>
          <div v-else-if="videos.length > 0" class="videos-grid">
            <video-card v-for="video in videos" :key="video._id" :video="video" />
          </div>
          <el-empty v-else description="该用户尚未上传视频" />
          
          <div v-if="hasMoreVideos" class="load-more">
            <el-button @click="loadMoreVideos" :loading="loadingMore">加载更多</el-button>
          </div>
        </el-tab-pane>
        
        <el-tab-pane label="关于" name="about">
          <div class="about-section">
            <h3>频道介绍</h3>
            <p v-if="user.bio">{{ user.bio }}</p>
            <p v-else>该用户尚未添加介绍</p>
            
            <div class="stats-section">
              <h3>频道数据</h3>
              <ul class="stats-list">
                <li>注册时间：{{ formatDate(user.createdAt) }}</li>
                <li>视频数量：{{ user.stats?.totalVideos || 0 }}</li>
                <li>总观看量：{{ formatViews(user.stats?.totalViews || 0) }}</li>
                <li>订阅者数：{{ formatSubscribers(user.subscribers?.length || 0) }}</li>
              </ul>
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>
    
    <el-empty v-else description="用户不存在或已被删除" />
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import { User } from '@element-plus/icons-vue';
import { useStore } from 'vuex';
import axios from '@/services/axios';
import VideoCard from '@/components/VideoCard.vue';
import { formatViews, formatDate, formatSubscribers } from '@/utils/formatters';

const route = useRoute();
const router = useRouter();
const store = useStore();

const user = ref(null);
const videos = ref([]);
const loadingUser = ref(true);
const loadingVideos = ref(true);
const loadingMore = ref(false);
const subscribing = ref(false);
const page = ref(1);
const limit = 12;
const hasMoreVideos = ref(true);
const activeTab = ref('videos');
const isSubscribed = ref(false);

const isLoggedIn = computed(() => store.getters['auth/isAuthenticated']);
const currentUser = computed(() => store.state.auth.user);

// 获取用户信息
const fetchUser = async () => {
  const userId = route.params.userId;
  if (!userId) {
    ElMessage.error('无效的用户ID');
    router.push('/');
    return;
  }
  
  loadingUser.value = true;
  try {
    const response = await axios.get(`/api/user/${userId}`);
    if (!response.data.user) {
      throw new Error('用户数据不存在');
    }
    user.value = response.data.user;
    
    // 检查当前用户是否已订阅该频道
    if (isLoggedIn.value && currentUser.value) {
      checkSubscriptionStatus();
    }
  } catch (error) {
    console.error('获取用户信息失败:', error);
    ElMessage.error('获取用户信息失败');
    user.value = null;
  } finally {
    loadingUser.value = false;
  }
};

// 获取用户视频
const fetchVideos = async (reset = false) => {
  const userId = route.params.userId;
  if (!userId) return;
  
  if (reset) {
    page.value = 1;
    videos.value = [];
    hasMoreVideos.value = true;
  }
  
  if (!hasMoreVideos.value) return;
  
  const isLoadingMore = !reset && videos.value.length > 0;
  if (isLoadingMore) {
    loadingMore.value = true;
  } else {
    loadingVideos.value = true;
  }
  
  try {
    const response = await axios.get(`/api/user/${userId}/videos`, {
      params: {
        page: page.value,
        limit: limit
      }
    });
    
    const newVideos = response.data.videos || [];
    videos.value = reset ? newVideos : [...videos.value, ...newVideos];
    hasMoreVideos.value = newVideos.length === limit;
    page.value++;
  } catch (error) {
    console.error('获取用户视频失败:', error);
    ElMessage.error('获取用户视频失败');
  } finally {
    loadingVideos.value = false;
    loadingMore.value = false;
  }
};

// 加载更多视频
const loadMoreVideos = () => {
  fetchVideos(false);
};

// 切换订阅状态
const toggleSubscription = async () => {
  if (!isLoggedIn.value) {
    ElMessage.warning('请先登录');
    return;
  }

  subscribing.value = true;
  try {
    const response = await axios.post(`/api/user/${user.value._id}/subscribe`);
    console.log('订阅响应:', response.data);
    
    isSubscribed.value = response.data.isSubscribed;
    
    if (user.value.subscribers) {
      if (isSubscribed.value) {
        if (!user.value.subscribers.includes(currentUser.value._id)) {
          user.value.subscribers.push(currentUser.value._id);
        }
      } else {
        user.value.subscribers = user.value.subscribers.filter(id => id !== currentUser.value._id.toString());
      }
    }
    
    ElMessage.success(isSubscribed.value ? '订阅成功' : '已取消订阅');
  } catch (error) {
    console.error('订阅操作失败:', error);
    console.log('错误详情:', error.response || error);
    ElMessage.error('订阅操作失败，请稍后重试');
  } finally {
    subscribing.value = false;
  }
};

// 检查当前用户是否已订阅该频道
const checkSubscriptionStatus = async () => {
  try {
    const response = await axios.get(`/api/user/${currentUser.value._id}/subscribed`, {
      params: { targetId: user.value._id }
    });
    isSubscribed.value = response.data.isSubscribed;
  } catch (error) {
    console.error('获取订阅状态失败:', error);
    isSubscribed.value = false;
  }
};

// 监听路由参数变化
watch(() => route.params.userId, (newId, oldId) => {
  if (newId && newId !== oldId) {
    fetchUser();
    fetchVideos(true);
  }
}, { immediate: true });

// 组件挂载时获取数据
onMounted(() => {
  if (route.params.userId) {
    fetchUser();
    fetchVideos(true);
  }
});
</script>

<style scoped>
.channel-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.channel-header {
  display: flex;
  align-items: center;
  margin-bottom: 30px;
  gap: 20px;
}

.channel-header-skeleton {
  display: flex;
  gap: 20px;
  align-items: center;
  margin-bottom: 30px;
}

.channel-info {
  flex: 1;
}

.channel-name {
  font-size: 24px;
  margin: 0 0 10px;
}

.channel-stats {
  display: flex;
  gap: 15px;
  color: #606266;
  margin-bottom: 10px;
}

.channel-bio {
  margin-bottom: 15px;
  color: #606266;
  white-space: pre-line;
}

.channel-tabs {
  margin-top: 20px;
}

.videos-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 20px;
  margin-top: 20px;
}

.load-more {
  text-align: center;
  margin-top: 30px;
}

.about-section {
  max-width: 800px;
}

.about-section h3 {
  margin: 20px 0 10px;
  font-size: 18px;
}

.stats-section {
  margin-top: 30px;
}

.stats-list {
  list-style: none;
  padding: 0;
}

.stats-list li {
  margin-bottom: 8px;
  color: #606266;
}

.loading-content {
  margin: 30px 0;
}
</style> 